﻿/*
 * Created by SharpDevelop.
 * User: Hellen(LongFan)
 * Date: 2015-12-30
 * Time: 16:36
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Threading;
using System.Collections.Concurrent;

namespace Comm
{
	/// <summary>
	/// Description of UpdataCurveThreadClass.
	/// </summary>
	public class UpdataCurveThreadClass
	{
		//Thread main while control
		private volatile bool UpdataCurveThEn = false;
		private volatile bool ThreadIsWorking = false;
		//Curve data queue
		public static ConcurrentQueue<byte> CurveDataQueue = new ConcurrentQueue<byte>();
		//control the comm received data fill to CurveDataQueue or not
		public static bool DataToCurveQueueEn = false;
		
		Thread UpdataCurveTh;
		//creat invoke delegate
		public delegate void UpdataCurveEventHandle(Double Ydata);
		public UpdataCurveEventHandle UpdataCurveInvokeHandle;
			
		public UpdataCurveThreadClass()
		{

		}
		
		public void StartUpdataCurveTh()
		{
			//make the main while start
			UpdataCurveThEn = true ;	//enable the thread main while
			DataToCurveQueueEn = true;	//enable the data fill to queue
			UpdataCurveTh = new Thread(new ThreadStart(UpdataCurveThFun));
			UpdataCurveTh.Start();
			//wait the thread to start
			while(!UpdataCurveTh.IsAlive);
		}
		
		public void StopUpadaCurveTh()
		{
			byte tempByte;
			UpdataCurveThEn = false;		//stop the data filled to the queue
			DataToCurveQueueEn = false;		//stop the main while
			//UpdataCurveTh.Join();			//wait the thread to stop
			//while(ThreadIsWorking);		//?why not working?
			while(0 < CurveDataQueue.Count )
			{//clear the CurveDataQueue
				CurveDataQueue.TryDequeue(out tempByte);
			}
		}
		//thread function
		private void UpdataCurveThFun()
		{
			byte[] DataByte = new byte[2];
			UInt32 ReIntData = 0;
			
			while(UpdataCurveThEn)
			{
				ThreadIsWorking = true;
				if( 8 <= CurveDataQueue.Count )
				{//the queue have data to show, dequeue the data
					for(int i=0;i<4;i++)
					{//every 4 point show one
						CurveDataQueue.TryDequeue(out DataByte[1]);
						CurveDataQueue.TryDequeue(out DataByte[0]);
						ReIntData = BitConverter.ToUInt16(DataByte,0);
					}
						//invoke the event
					UpdataCurveInvokeHandle( (((double)ReIntData)/65536) * 5 );
					Thread.Sleep(3);
				}
				else
				{
					Thread.Sleep(2);
				}
				ThreadIsWorking = false;
			}
		}
	}
}
